import { Ionicons } from '@expo/vector-icons';
import { useLocalSearchParams, useRouter } from 'expo-router';
import { useCallback, useEffect, useMemo, useState } from 'react';
import {
  ActivityIndicator,
  Alert,
  Pressable,
  ScrollView,
  StyleSheet,
  Switch,
  Text,
  TextInput,
  View,
} from 'react-native';
import { SafeAreaView } from 'react-native-safe-area-context';
import { Image } from 'expo-image';
import * as ImagePicker from 'expo-image-picker';

import { useAuth } from '@/context/auth-context';
import { apiRequest, uploadImage, ApiError } from '@/utils/api';
import { resolveAssetUrl } from '@/constants/config';
import { PageHeader } from '@/components/page-header';

type ApiAsset = {
  id: number;
  original_path: string;
  preview_path: string;
  thumb_path?: string;
  original_url: string;
  preview_url: string;
  thumb_url?: string;
};

type ProductImage = {
  id: number;
  sort_order: number;
  is_preview: boolean;
  asset_id?: number;
  asset?: ApiAsset | null;
};

type ProductDetail = {
  id: number;
  title: string;
  type: string;
  description: string;
  price: number;
  cover_asset_id?: number | null;
  cover_asset?: ApiAsset | null;
  images: ProductImage[];
  free_preview_limit?: number;
  is_published: boolean;
};

const palette = {
  background: '#fff7fb',
  surface: '#ffffff',
  accent: '#ff8fb1',
  accentDeep: '#ff6a9b',
  textPrimary: '#2f1f2b',
  textMuted: '#6a566a',
  border: 'rgba(214, 106, 138, 0.18)',
  danger: '#d64f7c',
};

export default function MerchantProductEditorScreen() {
  const params = useLocalSearchParams<{ id?: string | string[]; returnTo?: string | string[] }>();
  const router = useRouter();
  const { merchantToken: token } = useAuth();

  const productId = useMemo(() => {
    const value = Array.isArray(params.id) ? params.id[0] : params.id;
    return value ?? 'new';
  }, [params.id]);
  const isCreateMode = productId === 'new';
  const returnTo = useMemo(() => {
    const value = Array.isArray(params.returnTo) ? params.returnTo[0] : params.returnTo;
    return value ?? '/(merchant)/products';
  }, [params.returnTo]);

  const [title, setTitle] = useState('');
  const [type, setType] = useState('');
  const [price, setPrice] = useState('');
  const [description, setDescription] = useState('');
  const [coverAsset, setCoverAsset] = useState<{ id: number; url: string } | null>(null);
  const [gallery, setGallery] = useState<{ assetId: number; url: string; isPreview?: boolean }[]>([]);
  const [isPublished, setPublished] = useState(true);
  const [freePreviewLimit, setFreePreviewLimit] = useState('0');

  const [isLoading, setLoading] = useState(!isCreateMode);
  const [isSubmitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const handleBackPress = useCallback(() => {
    if (isCreateMode || params.returnTo) {
      router.replace(returnTo);
      return;
    }
    if (router.canGoBack()) {
      router.back();
    } else {
      router.replace(returnTo);
    }
  }, [isCreateMode, params.returnTo, returnTo, router]);

  const populateForm = useCallback((product: ProductDetail) => {
    setTitle(product.title);
    setType(product.type);
    setPrice(String(product.price ?? 0));
    setDescription(product.description ?? '');
    if (product.cover_asset && product.cover_asset.id) {
      const u = product.cover_asset.preview_url || product.cover_asset.thumb_url || product.cover_asset.original_url || '';
      setCoverAsset({ id: product.cover_asset.id, url: resolveAssetUrl(u) });
    } else {
      setCoverAsset(null);
    }
    setPublished(product.is_published ?? true);
    setFreePreviewLimit(String(product.free_preview_limit ?? 0));
    const images = (product.images || []).map((it) => ({
      assetId: it.asset?.id || it.asset_id!,
      url: resolveAssetUrl(it.asset?.thumb_url || it.asset?.preview_url || it.asset?.original_url || ''),
      isPreview: !!it.is_preview,
    })).filter((x) => x.assetId && x.url);
    setGallery(images);
  }, []);

  useEffect(() => {
    if (isCreateMode || !token) {
      setLoading(false);
      return;
    }

    const fetchDetail = async () => {
      try {
        const product = await apiRequest<ProductDetail>(`/products/${productId}`, {
          token,
        });
        populateForm(product);
        setError(null);
      } catch (err) {
        if (err instanceof ApiError && err.status === 401) {
          router.replace({
            pathname: '/(auth)/login',
            params: {
              channel: 'merchant',
              redirect: '/(merchant)/product/[id]',
              id: String(productId),
              returnTo,
            } as any,
          });
          return;
        }
        const message = err instanceof Error ? err.message : '无法加载商品详情，请稍后再试';
        setError(message);
      } finally {
        setLoading(false);
      }
    };

    fetchDetail();
  }, [isCreateMode, populateForm, productId, returnTo, router, token]);

  const handleRemoveGallery = useCallback((index: number) => {
    setGallery((prev) => {
      return prev.filter((_, idx) => idx !== index);
    });
  }, []);

  const pickImage = useCallback(async () => {
    const { status } = await ImagePicker.requestMediaLibraryPermissionsAsync();
    if (status !== 'granted') {
      Alert.alert('权限不足', '请在系统设置中授权访问相册以选择图片');
      return null;
    }
    const result = await ImagePicker.launchImageLibraryAsync({
      // expo-image-picker@15 expects an array of media type strings
      mediaTypes: ['images'],
      allowsMultipleSelection: false,
      quality: 1,
    });
    if (result.canceled || !result.assets?.length) return null;
    const asset = result.assets[0];
    return { uri: asset.uri, name: asset.fileName, type: asset.mimeType } as const;
  }, []);

  const handleUploadCover = useCallback(async () => {
    if (!token) return;
    const file = await pickImage();
    if (!file) return;
    try {
      const data = await uploadImage({ uri: file.uri, name: file.name, type: file.type }, token);
      setCoverAsset({ id: data.asset.id, url: resolveAssetUrl(data.preview_url || data.thumb_url || data.original_url) });
    } catch (err) {
      Alert.alert('上传失败', err instanceof Error ? err.message : '请稍后重试');
    }
  }, [pickImage, token]);

  const handleAddGalleryUpload = useCallback(async () => {
    if (!token) return;
    const file = await pickImage();
    if (!file) return;
    try {
      const data = await uploadImage({ uri: file.uri, name: file.name, type: file.type }, token);
      setGallery((prev) => [
        ...prev,
        { assetId: data.asset.id, url: resolveAssetUrl(data.thumb_url || data.preview_url || data.original_url) },
      ]);
    } catch (err) {
      Alert.alert('上传失败', err instanceof Error ? err.message : '请稍后重试');
    }
  }, [pickImage, token]);

  const handleSubmit = useCallback(async () => {
    if (!token) {
      setError('登录状态无效，请重新登录');
      return;
    }

    if (!title.trim()) {
      setError('请输入商品名称');
      return;
    }

    if (!type.trim()) {
      setError('请输入商品类型');
      return;
    }

    const priceValue = Number(price);
    if (Number.isNaN(priceValue) || priceValue < 0) {
      setError('请输入有效的商品价格');
      return;
    }

    const payload = {
      title: title.trim(),
      type: type.trim(),
      description: description.trim(),
      price: priceValue,
      cover_asset_id: coverAsset?.id ?? null,
      free_preview_limit: Math.max(0, Number(freePreviewLimit) || 0),
      images: gallery.map((g, idx) => ({ asset_id: g.assetId, sort_order: idx, is_preview: idx === 0 })),
      is_published: isPublished,
    } as const;

    setSubmitting(true);
    setError(null);

    try {
      if (isCreateMode) {
        await apiRequest('/products', {
          method: 'POST',
          token,
          body: payload,
        });
      } else {
        await apiRequest(`/products/${productId}`, {
          method: 'PUT',
          token,
          body: payload,
        });
      }

      Alert.alert('保存成功', '商品信息已更新', [
        {
          text: '好的',
          onPress: handleBackPress,
        },
      ]);
    } catch (err) {
      const message = err instanceof Error ? err.message : '保存失败，请稍后重试';
      setError(message);
    } finally {
      setSubmitting(false);
    }
  }, [
    coverAsset,
    description,
    gallery,
    handleBackPress,
    isCreateMode,
    isPublished,
    price,
    productId,
    title,
    freePreviewLimit,
    token,
    type,
  ]);

  const headerTitle = isCreateMode ? '新增商品' : '编辑商品';

  if (isLoading) {
    return (
      <SafeAreaView style={styles.container}>
        <PageHeader title={headerTitle} onBack={handleBackPress} backFallback={returnTo} />
        <View style={styles.centered}>
          <ActivityIndicator size="large" color={palette.accent} />
          <Text style={styles.loadingText}>正在加载商品信息...</Text>
        </View>
      </SafeAreaView>
    );
  }

  return (
    <SafeAreaView style={styles.container}>
      <PageHeader title={headerTitle} onBack={handleBackPress} backFallback={returnTo} />
      <ScrollView contentContainerStyle={styles.content} keyboardShouldPersistTaps="handled">
        <View style={styles.header}>
          <Text style={styles.subtitle}>
            填写商品基础信息，确保封面和图集风格统一
          </Text>
        </View>

        {error ? <Text style={styles.errorText}>{error}</Text> : null}

        <View style={styles.section}>
          <Text style={styles.label}>商品名称</Text>
          <TextInput
            value={title}
            onChangeText={setTitle}
            placeholder="请输入商品名称"
            placeholderTextColor={palette.textMuted}
            style={styles.input}
          />
        </View>

        <View style={styles.row}>
          <View style={styles.rowItem}>
            <Text style={styles.label}>商品类型</Text>
            <TextInput
              value={type}
              onChangeText={setType}
              placeholder="如：旅拍 / 活动摄影"
              placeholderTextColor={palette.textMuted}
              style={styles.input}
            />
          </View>
          <View style={styles.rowItem}>
            <Text style={styles.label}>价格（¥）</Text>
            <TextInput
              value={price}
              onChangeText={setPrice}
              keyboardType="decimal-pad"
              placeholder="输入价格"
              placeholderTextColor={palette.textMuted}
              style={styles.input}
            />
          </View>
        </View>

        <View style={styles.row}>
          <View style={styles.rowItem}>
            <Text style={styles.label}>免费预览数量</Text>
            <TextInput
              value={freePreviewLimit}
              onChangeText={setFreePreviewLimit}
              keyboardType="number-pad"
              placeholder="0 表示不开放预览"
              placeholderTextColor={palette.textMuted}
              style={styles.input}
            />
          </View>
          <View style={styles.rowItem} />
        </View>

        <View style={styles.section}>
          <Text style={styles.label}>商品介绍</Text>
          <TextInput
            value={description}
            onChangeText={setDescription}
            placeholder="填写拍摄亮点、服务内容、可提供的额外增值等信息"
            placeholderTextColor={palette.textMuted}
            style={[styles.input, styles.multilineInput]}
            multiline
            numberOfLines={4}
          />
        </View>

        <View style={styles.section}>
          <Text style={styles.label}>封面图</Text>
          <View style={{ gap: 10 }}>
            <Pressable style={styles.addButton} onPress={handleUploadCover}>
              <Ionicons name="cloud-upload-outline" size={16} color={palette.accentDeep} />
              <Text style={styles.addButtonText}>上传封面图片</Text>
            </Pressable>
            {coverAsset?.url ? (
              <View style={styles.previewBox}>
                <Image source={{ uri: coverAsset.url }} style={styles.previewImage} contentFit="cover" transition={200} />
              </View>
            ) : null}
          </View>
        </View>

        <View style={styles.section}>
          <View style={styles.galleryHeader}>
            <Text style={styles.label}>图集</Text>
            <Pressable style={styles.addButton} onPress={handleAddGalleryUpload}>
              <Ionicons name="cloud-upload-outline" size={16} color={palette.accentDeep} />
              <Text style={styles.addButtonText}>上传图片</Text>
            </Pressable>
          </View>
          <Text style={styles.galleryHint}>按展示顺序上传，可拖动调整顺序（当前按添加顺序）</Text>
          {gallery.map((g, index) => (
            <View key={`${g.assetId}-${index}`} style={[styles.galleryRow, { alignItems: 'center' }]}> 
              <View style={{ width: 72, height: 72, borderRadius: 12, overflow: 'hidden', backgroundColor: '#eee' }}>
                <Image source={{ uri: g.url }} style={{ width: '100%', height: '100%' }} contentFit="cover" />
              </View>
              <View style={{ flex: 1 }} />
              <Pressable style={styles.removeButton} onPress={() => handleRemoveGallery(index)}>
                <Ionicons name="trash-outline" size={16} color={palette.danger} />
              </Pressable>
            </View>
          ))}
        </View>

        <View style={styles.section}>
          <View style={styles.switchRow}>
            <Text style={styles.label}>商品状态</Text>
            <View style={styles.switchContainer}>
              <Text style={styles.switchText}>{isPublished ? '已上架' : '未上架'}</Text>
              <Switch
                value={isPublished}
                onValueChange={setPublished}
                trackColor={{ true: 'rgba(255,143,177,0.6)', false: '#d8d4db' }}
                thumbColor={isPublished ? palette.accentDeep : '#f4f3f4'}
              />
            </View>
          </View>
        </View>

        <Pressable
          style={[styles.submitButton, isSubmitting && styles.submitButtonDisabled]}
          onPress={handleSubmit}
          disabled={isSubmitting}
        >
          {isSubmitting ? (
            <ActivityIndicator color={palette.textPrimary} />
          ) : (
            <Text style={styles.submitText}>{isCreateMode ? '创建商品' : '保存更新'}</Text>
          )}
        </Pressable>
      </ScrollView>
    </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: palette.background,
  },
  content: {
    paddingHorizontal: 20,
    paddingVertical: 24,
    gap: 20,
  },
  centered: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: palette.background,
    gap: 12,
  },
  loadingText: {
    color: palette.textMuted,
    fontSize: 13,
  },
  header: {
    gap: 6,
  },
  title: {
    fontSize: 24,
    fontWeight: '700',
    color: palette.textPrimary,
  },
  subtitle: {
    fontSize: 13,
    color: palette.textMuted,
  },
  errorText: {
    color: palette.danger,
    fontSize: 13,
  },
  section: {
    gap: 8,
  },
  label: {
    fontSize: 13,
    fontWeight: '600',
    color: palette.textPrimary,
  },
  input: {
    borderRadius: 16,
    borderWidth: 1,
    borderColor: palette.border,
    backgroundColor: palette.surface,
    paddingHorizontal: 14,
    paddingVertical: 12,
    fontSize: 14,
    color: palette.textPrimary,
  },
  multilineInput: {
    height: 120,
    textAlignVertical: 'top',
  },
  row: {
    flexDirection: 'row',
    gap: 12,
  },
  rowItem: {
    flex: 1,
    gap: 8,
  },
  previewBox: {
    marginTop: 12,
    borderRadius: 20,
    overflow: 'hidden',
    borderWidth: 1,
    borderColor: palette.border,
  },
  previewImage: {
    width: '100%',
    height: 180,
  },
  galleryHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  galleryHint: {
    fontSize: 12,
    color: palette.textMuted,
  },
  galleryRow: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  galleryInput: {
    flex: 1,
  },
  addButton: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 4,
    paddingHorizontal: 10,
    paddingVertical: 6,
    borderRadius: 999,
    backgroundColor: 'rgba(255,143,177,0.18)',
  },
  addButtonText: {
    fontSize: 12,
    color: palette.accentDeep,
    fontWeight: '600',
  },
  removeButton: {
    width: 36,
    height: 36,
    borderRadius: 18,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'rgba(214,79,124,0.12)',
  },
  switchRow: {
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  switchContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: 8,
  },
  switchText: {
    fontSize: 13,
    color: palette.textMuted,
  },
  submitButton: {
    borderRadius: 22,
    paddingVertical: 14,
    alignItems: 'center',
    backgroundColor: palette.accent,
  },
  submitButtonDisabled: {
    opacity: 0.65,
  },
  submitText: {
    fontSize: 16,
    fontWeight: '700',
    color: palette.textPrimary,
    letterSpacing: 0.3,
  },
});
